package io.gitee.zhangbinhub.acp.cloud.resource.server.tools

import cn.dev33.satoken.context.SaHolder
import cn.dev33.satoken.oauth2.SaOAuth2Manager
import cn.dev33.satoken.oauth2.data.model.AccessTokenModel
import cn.dev33.satoken.oauth2.data.model.ClientTokenModel
import cn.dev33.satoken.oauth2.template.SaOAuth2Util
import cn.dev33.satoken.stp.StpUtil

object TokenTools {
    @JvmStatic
    fun getAccessToken(): String? =
        SaOAuth2Manager.getDataResolver().readAccessToken(SaHolder.getRequest())

    @JvmStatic
    fun getClientToken(): String? =
        SaOAuth2Manager.getDataResolver().readClientToken(SaHolder.getRequest())

    @JvmStatic
    @JvmOverloads
    fun getAccessTokenModel(accessToken: String? = null): AccessTokenModel? =
        SaOAuth2Util.getAccessToken(accessToken ?: getAccessToken())

    @JvmStatic
    @JvmOverloads
    fun getClientTokenModel(clientToken: String? = null): ClientTokenModel? =
        SaOAuth2Util.getClientToken(clientToken ?: getClientToken())

    @JvmStatic
    fun revokeAccessToken() {
        getAccessTokenModel()?.apply {
            revokeAccessToken(clientId, loginId)
        }
    }

    @JvmStatic
    fun revokeAccessToken(clientId: String?, loginId: Any?) {
        SaOAuth2Util.revokeAccessTokenByIndex(clientId, loginId)
        StpUtil.logout(loginId, clientId)
    }

    @JvmStatic
    fun revokeClientToken() {
        getClientTokenModel()?.apply {
            revokeClientToken(clientId)
        }
    }

    @JvmStatic
    fun revokeClientToken(clientId: String?) {
        SaOAuth2Util.revokeClientTokenByIndex(clientId)
    }

    @JvmStatic
    fun revokeRefreshToken() {
        getAccessTokenModel()?.apply {
            revokeRefreshToken(clientId, loginId)
        }
    }

    @JvmStatic
    fun revokeRefreshToken(clientId: String?, loginId: Any?) {
        SaOAuth2Util.revokeRefreshTokenByIndex(clientId, loginId)
    }
}